import { createRouter, createWebHashHistory } from "vue-router";
import ConstantRoutes from "./constant-routes";
import AsyncRoutes from "./async-routes";
import { getToken } from "@/utils/auth";

/** 常住路由 */
export const constantRoutes = ConstantRoutes;
/** 动态路由 */
export const asyncRoutes = AsyncRoutes;

console.log("constantRoutes", constantRoutes);
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes,
});

/** 重置路由 */
export function resetRouter() {
  //所有动态路由必须带有name属性,否则可能会不能完全重置
  try {
    router.getRoutes().forEach((route) => {
      const { name, meta, path } = route;
      if (name && name !== "Home") {
        router.hasRoute(name) && router.removeRoute(name);
      }
    });
  } catch (error) {
    //强制刷新浏览器
    window.location.reload();
  }
}

//路由白名单
const WHITEROUTER = ["/login"];
router.beforeEach(async (to, from, next) => {
  document.title = "收银系统";
  console.log("111", getToken());
  const token = getToken();
  //判断是否拥有token
  if (token && token != "undefined") {
    if (to.path === "/login") {
      //已登录,跳转到首页
      next({ path: "/" });
    } else {
      //判断权限等, 待做
      next();
    }
  } else {
    //没有token
    if (WHITEROUTER.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
